import { Component } from "react";
import PubSub from "pubsub-js";

class User2 extends Component {
  token = "";
  startPubSub = () => {
    if (this.token) return;
    this.token = PubSub.subscribe("USERMSG", (data, msg) => {
      console.log("data:", data, "----msg:", msg);
    });
    console.log("我已经开始订阅");
  };
  cancelPubSub = () => {
    if (!this.token) return;
    PubSub.unsubscribe(this.token);
    this.token = "";
    console.log("我已经取消订阅");
  };
  componentWillUnmount() {
    this.cancelPubSub();
  }
  render() {
    return (
      <div>
        <button onClick={this.startPubSub}>开始订阅</button>
        <br></br>
        <button onClick={this.cancelPubSub}>取消订阅</button>
      </div>
    );
  }
}
export default User2;
